// 实现这个项目的构建任务
const { src, dest, parallel, series, watch } = require('gulp')

const del = require('del')
const browserSync = require('browser-sync')
const loadPlugins = require('gulp-load-plugins')
const plugins = loadPlugins()
const bs = browserSync.create()
const ts = plugins.typescript
const tsProject = ts.createProject('tsconfig.json')

const data = {
  menus: require('./config/menu.json'),
  pkg: require('./package.json'),
  date: new Date()
}

const clean = () => del(['dist', 'temp'])

const style = () =>
  src('src/assets/styles/*.scss', { base: 'src' })
    .pipe(plugins.sass({ outputStyle: 'expanded' }).on('error', plugins.sass.logError)) // 设置样式格式为expanded
    .pipe(dest('temp'))
    .pipe(bs.stream())

const script = () =>
  src('src/assets/scripts/**/*.ts', { base: 'src' }) // 找到scripts下所有的ts文件
    // .pipe(plugins.babel({ presets: ['@babel/preset-env'] })) // 对通过babel对ES6语法进行翻译
    .pipe(tsProject())
    .js.pipe(dest('temp'))
    .pipe(bs.stream())

const page = () =>
  src('src/*.html', { base: 'src' })
    .pipe(plugins.swig({ data, defaults: { cache: false } })) // 防止模板缓存导致页面不能及时更新
    .pipe(dest('temp'))
    .pipe(bs.stream())

const image = () =>
  src('src/assets/images/**', { base: 'src' })
    .pipe(plugins.imagemin())  // 对图片进行压缩
    .pipe(dest('dist'))

const font = () =>
  src('src/assets/fonts/**', { base: 'src' })
    .pipe(plugins.imagemin()) // 对svg文件进行压缩
    .pipe(dest('dist'))

const extra = () =>
  src('public/**', { base: 'public' })
    .pipe(dest('dist'))

const serve = () => {
  watch('src/assets/styles/*.scss', style)
  watch('src/assets/scripts/*.js', script)
  watch('src/*.html', page)
  watch([
    'src/assets/images/**',
    'src/assets/fonts/**',
    'public/**'
  ], bs.stream)

  bs.init({
    notify: false,
    port: 2080,
    server: {
      baseDir: ['temp', 'src', 'public'],
      routes: {
        '/node_modules': 'node_modules'
      }
    }
  })
}

const useref = () =>
  src('temp/*.html', { base: 'temp' })
    .pipe(plugins.useref({ searchPath: ['temp', '.'] }))
    // html js css
    .pipe(plugins.if(/\.js$/, plugins.uglify()))
    .pipe(plugins.if(/\.css$/, plugins.cleanCss()))
    .pipe(plugins.if(/\.html$/, plugins.htmlmin({
      collapseWhitespace: true,
      minifyCSS: true,
      minifyJS: true
    })))
    .pipe(dest('dist'))

const compile = parallel(style, script, page)

// 上线之前执行的任务
const build =  series(
  clean,
  parallel(
    series(compile, useref),
    image,
    font,
    extra
  )
)

const develop = series(compile, serve)

module.exports = {
  clean,
  page,
  build,
  develop,
}
